package com.cens.mall.seckill.config;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class RabbitConfig {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定制RabbitTemplate
     * 1、spring.rabbitmq.publisher-confirms=true
     * 2、设置确认回调 ConfirmCallback
     * 3、
     * RabbitConfig对象创建完成后执行该方法
     */
    @PostConstruct
    public RabbitTemplate initRabbitTemplate() {
        rabbitTemplate.setConfirmCallback(
                /*
                 * publisher 发送给 broker 回调
                 * correlationData 当前消息的唯一id
                 * ack 表示消息是否成功收到
                 * cause 失败原因
                 */
                (correlationData, ack, cause) -> {
                    System.out.println("confirm callback correlationData: " + correlationData + " ack: " + ack);
                    System.out.println("error cause: " + cause);
                }
        );
        rabbitTemplate.setReturnCallback(
                /*
                 * exchange 发送给 queue 回调
                 * 消息没有投递给指定的queue（即抵达失败），则触发此回调
                 * message： 投递失败的消息详细信息
                 * replyCode： 回复的状态码
                 * replyCode： 回复的文本内容
                 * exchange： 消息发给那个交换机
                 * routingKey： 消息使用的路由键
                 */
                (message, replyCode, replyText, exchange, routingKey) -> {
                    System.out.println("return callback message:" + message + " replyCode:" + replyCode);
                    System.out.println("return callback replyText:" + replyText + " exchange:" + exchange);
                    System.out.println("return callback routingKey:" + routingKey );
                }
        );
        return rabbitTemplate;
    }
}
